home *** CD-ROM | disk | FTP | other *** search
- Path: fas.harvard.edu!berriz
- From: Zorro <berriz@husc.harvard.edu>
- Newsgroups: comp.lang.c
- Subject: Weird perl-C interaction (rand)
- Date: 17 Jan 1996 18:36:32 GMT
- Organization: Harvard University, Cambridge, Massachusetts
- Message-ID: <4djfjg$l45@decaxp.harvard.edu>
- Reply-To: berriz@husc.harvard.edu
- NNTP-Posting-Host: fas.harvard.edu
- Keywords: perl, C, rand, random
- X-Newsreader: NN version 6.5.0 #3 (NOV)
- Originator: berriz@fas.harvard.edu
-
-
-
- I tried the following in a perl script to generate seeds to be given
- as arguments in calls to a C program:
-
- $seed = int(rand((2**31) -1)) + 1;
-
- The C program stores this value in its own local variable "seed" and,
- of course, uses it to seed its random number generator:
-
- srandom(seed);
-
- Then, the C program calls random(), and takes the modulo 32768 of the
- returned value.
-
- u = random() % 32768;
-
- To my utter wilderment the resulting number u is *always* the same,
- even though the seeds produced by the perl script are always
- different.
-
- I got around the problem by switching the perl code to
-
- $seed = int(rand((2**14) -1)) + 1;
-
- ...but I'm clueless as to what's going on. Does anybody know? More
- to the point, is my "solution" OK?
-
- FWIW, I'm running this on an IBM RS/6000, under AIX 3.2.5. Below are
- toy versions of the perl script ("mumble") and the C program
- ("frotz.c", compiled to the executable "frotz"); they exhibit the
- problem described above. I've also included mumble's output.
-
- Thanks in advance,
-
- Z.
-
-
- ... mumble ..................................................................
-
- #!/usr/local/bin/perl -w
-
- srand(time|$$);
-
- for(1..10) {
- $seed = int(rand((2**31) -1)) +1;
- system("frotz $seed");
- }
-
- ..........................................................................
-
- /* frotz.c */
- void main(int argc, char *argv[]) {
-
- int x;
- unsigned int seed;
-
- seed = (unsigned) atoi(argv[1]);
- srandom(seed);
- x = random();
-
- printf("%12d %12d %6d\n", seed, x, x % 32768);
- }
-
- ..........................................................................
- $ mumble
- 494862336 1155565115 1595
- 614662144 884639291 1595
- 963575808 1387824699 1595
- 2010775552 1296303675 1595
- 1405616128 1142359611 1595
- 84934656 994772539 1595
- 1688469504 272434747 1595
- 1452736512 1738311227 1595
- 402128896 1452213819 1595
- 1499332608 789448251 1595
-